package sd.settemmezzo.util;

import java.util.Vector;

import sd.settemmezzo.common.Player;

public class Ring extends Vector<Player> {
	private static final long serialVersionUID = 6284799593714129475L;

	public synchronized Player getNext(Player p) {
		
		// return this.get((this.indexOf(p) + 1) % this.size());
		
		if (this.indexOf(p) != this.size() - 1) {
			return this.get(this.indexOf(p) + 1);
		} else {
			return this.firstElement();
		}
	}
	
	public synchronized Player getNext(int id) {
		for (Player p : this) {
			if (p.getId() == id)
				return this.getNext(p);
		}
		return null;
	}
	
	public synchronized Player getPrevious(Player p) {
		if (this.indexOf(p) == 0) {
			return this.lastElement();
		} else {
			return this.get(this.indexOf(p) - 1);
		}
	}
	
	public synchronized Player getPrevious(int id) {
		for (Player p : this) {
			if (p.getId() == id)
				return this.getPrevious(p);
		}
		return null;
	}
	
	public synchronized void configMazziere(Player p) {
		int pos = 0;
		Player pi;
		while (this.lastElement() != p) {
			pi = this.get(indexOf(p) + 1);
			this.remove(pi);
			this.insertElementAt(pi, pos++);
		}
	}
	
	public synchronized void configMazziere(int id) {
		Player p = null;
		for (Player pi : this) {
			if (pi.getId() == id)
				p = pi;
		}
		if (p != null) 
			this.configMazziere(p);
	}
	
	public synchronized void crash(Player p) {
		if (p == this.lastElement())
			this.configMazziere(this.getNext(p));
		this.remove(p);
	}
	
	public synchronized void crash(int id) {
		for (Player p : this) {
			if (p.getId() == id) {
				this.crash(p);
				return;
			}
		}
	}
	
	public boolean contains(Player p) {
		for (Player pi : this)
			if (pi.getId() == p.getId()) {
				return true;
			}
		return false;
	}
	
	public boolean contains(int id) {
		for (Player pi : this)
			if (pi.getId() == id) {
				return true;
			}
		return false;
	}
	
	public synchronized Player getMazziere() {
		return this.lastElement();
	}
	
}
